import { login, codeLogin, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    userinfo: null,
    roles: [],
    permissions: []
  }
}

const state = getDefaultState()

const mutations = {
  // RESET_STATE: (state) => {
  //   Object.assign(state, getDefaultState())
  // },
  SET_USERINFO: (state, userinfo) => {
    state.userinfo = userinfo
    // const { trading_location_accounts = [] } = userinfo || {}
    // if (trading_location_accounts.length) {
    //   const SJS = trading_location_accounts.find((item) => item.trading_location_id === 1) || {}
    //   state.isBind_sjs = dayjs().isBefore(SJS.service_expired_at)
    // }
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    console.log(userInfo, '-------------------------userInfo')
    const { username, password, captcha, key } = userInfo
    return new Promise((resolve, reject) => {
      login({ phone: username.trim(), password: password, captcha: captcha, key: key }).then(response => {
        const { data } = response
        console.log(data, '---------------getInfo')
        commit('SET_ROLES', data.roles)
        commit('SET_PERMISSIONS', data.permissions)
        localStorage.setItem('roles', JSON.stringify(data.roles))
        localStorage.setItem('permissions', JSON.stringify(data.permissions))
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        commit('SET_USERINFO', data)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  codeLogin({ commit }, userInfo) {
    console.log(userInfo, '-------------------------userInfo')
    const { phone, code } = userInfo
    return new Promise((resolve, reject) => {
      codeLogin({ phone: phone.trim(), code: code }).then(response => {
        const { data } = response
        console.log(data, '---------------getInfo')
        commit('SET_ROLES', data.roles)
        commit('SET_PERMISSIONS', data.permissions)
        localStorage.setItem('roles', JSON.stringify(data.roles))
        localStorage.setItem('permissions', JSON.stringify(data.permissions))
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        commit('SET_USERINFO', data)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { name, avatar, roles, permissions } = data
        console.log(roles, '---------------------------mmmmmmmmmmmmmmroles')
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_USERINFO', data)
        commit('SET_ROLES', roles)
        commit('SET_PERMISSIONS', permissions)
        localStorage.setItem('roles', JSON.stringify(roles))
        localStorage.setItem('permissions', JSON.stringify(data.permissions))
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        location.reload()
        commit('SET_TOKEN', '')
        commit('SET_USERINFO', null)
        commit('SET_ROLES', null)
        commit('SET_PERMISSIONS', null)
        removeToken() // must remove  token  first
        resetRouter()
        // commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      console.log(resolve, '--------------------------- resetRouter()')
      commit('SET_TOKEN', '')
      commit('SET_USERINFO', null)
      commit('SET_ROLES', null)
      commit('SET_PERMISSIONS', null)
      removeToken() // must remove  token  first
      // commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

